<template>
  <div class="content-wapper" content-wapper>
    <a-tabs default-active-key="1" @change="callback">
      <a-tab-pane key="1" tab="直播商品">
        <!-- 直播管理 -->
        <a-spin class="live-review" tip="加载中..." :spinning="isLoading">
          <!-- 筛选 -->
          <div class="filter">
            <div class="l search-box">
              <div>
                <span>站点：</span>
                <a-select
                  allowClear
                  style="width:160px;"
                  showSearch
                  :defaultActiveFirstOption="false"
                  :filterOption="false"
                  @search="getAllStation($event)"
                  @change="changeLocation"
                  v-model="search.locationId"
                  placeholder="请选择站点"
                  class="filter-select"
                >
                  <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
                </a-select>
              </div>
              <div>
                <span>产品ID：</span>
                <a-input-search oninput="value = value.replace(/[^\d]/g, '')" style="width:240px;" placeholder="输入产品ID" allowClear v-model="search.productId" @search="handleByQueryCond" />
              </div>
              <div>
                <span>产品名称：</span>
                <a-input-search type="text" style="width:240px;" placeholder="输入产品名称" allowClear v-model="search.productName" @search="handleByQueryCond" />
              </div>
            </div>
            <div class="r">
              <a-space>
                <a-button type="primary" style="background:#1d6fe9;" @click="addProductVisible = true">新增产品</a-button>
                <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9;">查询</a-button>
                <a-button type="primary" :disabled="productSelectedRowKeys.length === 0" @click="onProductBatchDel" :style="productSelectedRowKeys.length === 0 ? {} : { background: '#1d6fe9' }">
                  批量删除
                </a-button>
              </a-space>
            </div>
          </div>

          <!-- 表格 -->
          <div class="main-body">
            <a-table
              :columns="tableColumns"
              :row-selection="{ selectedRowKeys: productSelectedRowKeys, onChange: (keys) => (productSelectedRowKeys = keys), columnWidth: 20 }"
              :pagination="false"
              :data-source="dyLiveProductList"
              :scroll="{ x: 900, y: tableHeight - 60 }"
              rowKey="id"
            >
              <template slot="urls" slot-scope="text, record">
                <template v-if="record.urls && record.urls.length > 0">
                  <div>
                    <upload v-show="record.urls && record.urls.length > 0" :limit="record.urls.length" disabled :value="record.urls"> </upload>
                  </div>
                </template>
                <template v-else>
                  无
                </template>
              </template>
              <!-- 产品佣金 -->
              <template slot="commission" slot-scope="text, record">
                <div>大达人：{{ record.superFirstMoney }}.{{ record.firstMoney }}</div>
                <div>小达人：{{ record.secondMoney }}</div>
              </template>
              <!-- 操作按钮 -->
              <template slot="action" slot-scope="text, record">
                <a-button v-if="record.isVisible === 0" type="link" herf="javascript:;" size="small" @click="showUp(record.id)">上架</a-button>
                <a-button v-if="record.isVisible === 1" type="link" herf="javascript:;" size="small" @click="showDown(record.id)">下架</a-button>
                <a-button type="link" herf="javascript:;" size="small" @click="handleDel(record.id)">删除</a-button>
                <a-button type="link" herf="javascript:;" size="small" @click="handleOpenSort(record.id, record.sequence)">排序</a-button>
                <!-- <a-button type="link" herf="javascript:;" size="small" @click="handleOpenCommission(record.id, record.superFirstMoney, record.firstMoney, record.secondMoney)">佣金设置</a-button> -->
                <a-button type="link" herf="javascript:;" size="small" @click="showPlacedTop(record.id)">置顶</a-button>
              </template>
            </a-table>
          </div>

          <!-- 新增产品弹窗 -->
          <a-modal v-model="addProductVisible" title="新增产品" @ok="handleAddProduct" @cancel="addClose">
            <a-form-model :model="addProductForm" ref="addProductForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
              <a-form-model-item label="站点" prop="locationId" :rules="[{ required: true, trigger: 'change', message: '请选择站点' }]">
                <a-select allowClear showSearch :defaultActiveFirstOption="false" :filterOption="false" @search="getAllStation($event)" v-model="addProductForm.locationId" placeholder="请选择站点">
                  <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="产品Id" prop="productId" :rules="[{ required: true, trigger: 'change', message: '请填写产品id' }]">
                <a-input allowClear oninput="value = value.replace(/[^\d]/g, '')" v-model="addProductForm.productId" />
              </a-form-model-item>
              <a-form-model-item label="产品图片" prop="pictureUrl" :rules="[{ required: true, trigger: 'blur', message: '请上传产品图片' }]">
                <upload :limit="1" v-model="addProductForm.pictureUrl" />
              </a-form-model-item>
            </a-form-model>
          </a-modal>

          <!-- 排序弹窗 -->
          <a-modal v-model="sortingVisible" title="修改排序" @ok="handleSort">
            <a-form-model ref="sortForm" :model="sortForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-form-model-item label="当前排序" prop="sequence" :rules="[{ required: true, message: '排序不能为空', trigger: 'change' }]">
                <a-input allowClear oninput="value = value.replace(/[^\d]/g, '')" v-model="sortForm.sequence" />
              </a-form-model-item>
            </a-form-model>
          </a-modal>

          <!-- 佣金设置弹窗 -->
          <a-modal v-model="commissionVisible" title="佣金设置" @ok="handleCommission">
            <a-form-model ref="commissionForm" :model="commissionForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-form-model-item label="大中达人佣金" prop="bigMoneyStr" :rules="[{ required: true, message: '大中达人佣金不能为空', trigger: 'change' }]">
                <a-input v-model="commissionForm.bigMoneyStr" />
              </a-form-model-item>
              <a-form-model-item label="小达人佣金" prop="secondMoney" :rules="[{ required: true, message: '小达人佣金不能为空', trigger: 'change' }]">
                <a-input v-model="commissionForm.secondMoney" />
              </a-form-model-item>
            </a-form-model>
          </a-modal>

          <!-- 分页 -->
          <div class="paging-container">
            <a-pagination
              :pageSize="pagination.pageSize"
              v-model="pagination.pageIndex"
              :total="pagination.total"
              showQuickJumper
              showLessItems
              :showTotal="(total) => `共 ${total} 条`"
              style="margin: 10px auto;"
              @change="handlePageChange"
            />
          </div>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane key="2" tab="直播数据统计">
        <a-spin class="statist-wapper" tip="加载中..." :spinning="isDataLoading">
          <!-- 筛选 -->
          <div class="filter">
            <div class="l">
              <span>站点：</span>
              <a-select
                style="width:160px;"
                showSearch
                :defaultActiveFirstOption="false"
                :filterOption="false"
                @search="getAllStation($event)"
                @change="changeDataLocation"
                v-model="dataSearch.locationId"
                placeholder="请选择站点"
                class="filter-select"
              >
                <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
              </a-select>
              <span>日期：</span>
              <a-range-picker @change="clearTime" :showTime="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }" format="YYYY-MM-DD HH:mm:ss" @ok="changeTime" v-model="dataSearch.selectDate" />
              <a-select v-model="dataSearch.status" style="width: 120px" @change="liveAllData">
                <a-select-option :value="''"> 全部 </a-select-option>
                <a-select-option :value="3"> 已核销 </a-select-option>
              </a-select>
            </div>

            <div class="r">
              <a-button type="primary" @click="liveAllData" style="background:#1d6fe9">查询</a-button>
            </div>
          </div>
          <div class="all-data">
            <div class="data-item total-data">
              <div class="img-box"><img src="@/assets/images/statist/icon_sjtj_zls@3x.png" alt="" /></div>
              <div class="data-item-item">
                <p class="number-p">
                  <a-statistic :value="(totalData.orderMoney || 0) | fenToYuan" />
                </p>
                <p class="text-p">总流水</p>
              </div>
              <div class="data-item-item">
                <p class="number-p">
                  <a-statistic :value="totalData.orderNum || 0" />
                </p>
                <p class="text-p">总订单</p>
              </div>
              <div class="data-item-item">
                <p class="number-p">
                  <a-statistic :value="totalData.productNum || 0" />
                </p>
                <p class="text-p">商品数量</p>
              </div>
            </div>
          </div>
          <!-- 表格 -->
          <div class="main-body">
            <a-table :columns="dataTableColumns" :pagination="false" :data-source="siteDataList" :scroll="{ x: 900, y: tableHeight - 180 }" rowKey="locationId"></a-table>
          </div>

          <!-- 分页 -->
          <div class="paging-container">
            <a-pagination
              :pageSize="dataPagination.pageSize"
              v-model="dataPagination.pageIndex"
              :total="dataPagination.total"
              showQuickJumper
              showLessItems
              :showTotal="(total) => `共 ${total} 条`"
              style="margin: 10px auto;text-align:right;"
              @change="dataHandlePageChange"
            />
          </div>
        </a-spin>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import {
  pointLocationList,
  getLiveProductList,
  fixLiveProduct,
  topLiveProduct,
  addLiveProduct,
  fixLiveProductMoney,
  locationList,
  liveProudctDel,
  liveProudctDownUp,
  liveProudctTotalPoint,
  liveProudctStPoint
} from '@/service'
import upload from '@/components/upload/upload'
import moment from 'moment'
import debounce from 'lodash/debounce'
import { getToken } from '@/util/method'
import { safeDiv } from '@/util'
export default {
  name: 'pointLiveIndex',
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    return {
      moment,
      headers: {
        Authorization: getToken()
      },
      //   新增产品弹窗状态
      addProductVisible: false,
      addProductForm: {
        locationId: null,
        productId: null,
        pictureUrl: []
      },
      //   排序弹窗状态
      sortingVisible: false,
      sortForm: {
        id: null,
        sequence: null
      },
      //   佣金弹窗状态
      commissionVisible: false,
      commissionForm: {
        liveId: null,
        bigMoneyStr: null,
        secondMoney: null
      },
      // loading是否显示
      isLoading: false,
      isDataLoading: false,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      dataPagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // 全部站点
      allStation: [],
      // table数据查询条件
      search: {
        locationId: undefined, // 站点id
        productId: null, // 产品id
        productName: '' // 产品名称
      },
      dataSearch: {
        locationId: undefined, // 站点id
        selectDate: [], // 选择时间
        status: ''
      },
      // 订单列表
      dyLiveProductList: [],
      tableColumns: [
        { title: '产品ID', width: 76, dataIndex: 'bizProductId' },
        { title: '产品名称', width: 140, dataIndex: 'bizProductName', scopedSlots: { customRender: 'cpName' } },
        { title: '产品排序', width: 140, dataIndex: 'sequence' },
        { title: '产品佣金', width: 140, scopedSlots: { customRender: 'commission' } },
        { title: '操作', width: 130, dataIndex: 'action', scopedSlots: { customRender: 'action' } }
      ],
      productSelectedRowKeys: [], // 直播商品选择行
      // 总统计数
      totalData: {},
      // 站点列表
      locationListData: [],
      siteDataList: []
    }
  },
  components: {
    upload
  },
  // 过滤器
  filters: {
    // 处理分-元
    fenToYuan(val) {
      if (!val) return 0
      return (val / 100).toFixed(2)
    }
  },
  computed: {
    // table配置
    dataTableColumns() {
      return [
        { title: '产品id', width: 150, dataIndex: 'bizProductId' },
        { title: '站点', width: 150, dataIndex: 'city' },
        {
          title: '订单流水',
          width: 120,
          dataIndex: 'orderMoney',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        },
        { title: '订单量', width: 150, dataIndex: 'orderNum' },
        { title: '产品名称', width: 120, dataIndex: 'productTitle' }
      ]
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // tab切换
    callback(key) {
      if (key === '1') {
        this.search = {
          locationId: undefined, // 站点id
          productId: null, // 产品id
          productName: '' // 产品名称
        }
        this.pagination.pageIndex = 1
        this.query()
      } else if (key === '2') {
        this.searchGoods = {
          selectDate: [],
          locationId: undefined
        }
        if (this.allStation && this.allStation.length > 0) {
          this.dataSearch.locationId = this.allStation[0].id || undefined
          this.dataPagination.pageIndex = 1
          this.liveAllData()
        }
      }
    },
    //   新增产品
    handleAddProduct() {
      this.$refs.addProductForm.validate(async (valid) => {
        if (valid) {
          let { locationId, productId, pictureUrl } = this.addProductForm
          let res = await addLiveProduct({ locationId, productId, pictureUrl: pictureUrl[0] })
          console.log(res)
          this.initQuery()
          this.addProductVisible = false
        } else {
          return false
        }
      })
    },
    // 站点列表
    async getLocationList() {
      await locationList({ city: '' }).then((res = []) => {
        this.locationListData = res
      })
    },
    // 关闭新增弹窗
    addClose() {
      this.addProductForm = {
        locationId: null,
        productId: null,
        pictureUrl: []
      }
      this.getAllStation()
      this.$refs.addProductForm.resetFields()
    },
    // 打开修改弹窗
    handleOpenSort(id, sequence) {
      this.sortingVisible = true
      this.sortForm = { id, sequence }
    },
    // 删除
    handleDel(id = '') {
      const { $messageSend, $confirm, query } = this
      $confirm({
        title: '删除操作',
        content: '确定要删除该条数据吗？',
        onOk: () => {
          // 发送请求
          return liveProudctDel({ isDelete: 1, liveId: id })
            .then((res) => {
              query()
              $messageSend.success('操作成功')
            })
            .catch((err) => err)
        }
      })
    },

    // 修改排序
    handleSort() {
      this.$refs.sortForm.validate(async (valid) => {
        if (valid) {
          let res = await fixLiveProduct(this.sortForm)
          console.log(res)
          this.query()
          this.sortingVisible = false
        } else {
          return false
        }
      })
    },
    // 打开佣金
    handleOpenCommission(id, superFirstMoney, firstMoney, secondMoney) {
      this.commissionVisible = true
      this.commissionForm = { liveId: id, bigMoneyStr: superFirstMoney + '.' + firstMoney, secondMoney }
    },
    // 修改佣金
    handleCommission() {
      this.$refs.commissionForm.validate(async (valid) => {
        if (valid) {
          let res = await fixLiveProductMoney(this.commissionForm)
          console.log(res)
          this.query()
          this.commissionVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },

    handleDataByQueryCond() {
      this.dataPagination.pageIndex = 1
      this.liveAllData()
    },
    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },
    dataHandlePageChange(num) {
      this.dataPagination.pageIndex = num
      this.getLiveDatas()
    },

    getAllStation(e) {
      return new Promise((resolve, reject) => {
        pointLocationList({ city: e })
          .then((res) => {
            this.allStation = res
            resolve(res)
          })
          .catch(() => {
            return reject(new Error('接口出错'))
          })
      })
    },
    // 选择了站点
    changeLocation() {
      this.initQuery()
    },
    changeDataLocation(e) {
      this.liveAllData()
    },
    changeTime(value) {
      if (value && value.length > 0) {
        this.selectDate = [moment(value[0]).format('YYYY-MM-DD HH:mm:ss'), moment(value[1]).format('YYYY-MM-DD HH:mm:ss')]
        this.liveAllData()
      } else {
        this.$messageSend.error('请选择时间')
      }
    },
    clearTime(val, string) {
      if (val && val.length === 0) {
        this.selectDate = []
        this.liveAllData()
      }
    },
    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { locationId, productId, productName } = this.search

      return {
        pageIndex,
        pageSize,
        locationId,
        productId,
        productName
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, productId, productName } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          productId: productId || '',
          productName: productName || ''
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },
    /**
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      getLiveProductList(this.getParams())
        .then((rs) => {
          this.dyLiveProductList = Object.freeze(rs.dyLiveProductList) || []
          this.pagination.total = rs.total || 0
          this.productSelectedRowKeys = []
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    async showUp(id) {
      await liveProudctDownUp({ liveId: id, isVisible: 1 })
      this.query()
    },
    async showDown(id) {
      await liveProudctDownUp({ liveId: id, isVisible: 0 })
      this.query()
    },
    async showPlacedTop(id) {
      await topLiveProduct({ liveId: id })
      this.query()
    },
    // 直播商品批量删除
    onProductBatchDel() {
      const { $confirm, $messageSend, query } = this
      $confirm({
        title: '删除操作',
        content: '确定要删选中数据吗？',
        onOk: () => {
          return liveProudctDel({ isDelete: 1, liveId: this.productSelectedRowKeys.join(',') })
            .then((res) => {
              query()
              $messageSend.success('操作成功')
            })
            .catch((err) => err)
        }
      })
    },
    // 直播数据统计相关
    // 拿参数
    getDataParams() {
      const { pageIndex, pageSize } = this.dataPagination
      const { locationId, selectDate, status } = this.dataSearch
      return {
        pageIndex,
        pageSize,
        locationId,
        status,
        timeEnd: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD HH:mm:ss') : undefined,
        timeStart: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD HH:mm:ss') : undefined
      }
    },
    getTotalData() {
      liveProudctTotalPoint(this.getDataParams()).then((res = {}) => {
        this.totalData = res
      })
    },
    getLiveDatas() {
      liveProudctStPoint(this.getDataParams()).then((res = {}) => {
        this.siteDataList = res.detailStatisticsList || []
        this.dataPagination.total = res.total || 0
      })
    },
    liveAllData() {
      const { getTotalData, getLiveDatas, dataSearch, $messageSend } = this
      if (!dataSearch.locationId) {
        $messageSend.error('直播站点不能为空')
        return false
      }
      this.isDataLoading = true
      Promise.all([getTotalData(), getLiveDatas()])
        .then(() => {
          this.isDataLoading = false
        })
        .catch(() => {
          this.isDataLoading = false
        })
    }
  },

  mounted() {
    this.setSearch()
    this.getAllStation()
    this.initQuery()
  }
}
</script>

<style lang="less" scoped>
.live-review {
  padding: 0 0 16px 0;
}
/deep/ .ant-tabs {
  width: 100%;
}
/deep/ .ant-tabs-nav {
  padding: 1px 2px;
  height: 32px;
  width: 200px;
  background: #eeeeee;
  border-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}
/deep/ .ant-tabs-nav-wrap {
  margin-bottom: 2px;
}
/deep/ .ant-tabs-nav .ant-tabs-tab {
  height: 12px;
  width: 96px;
  text-align: center;
  line-height: 13px;
  background: #eeeeee;
  border-right: 1px solid #cccccc;
  // color: #333;
  padding: 0;
  margin: 0;
  transition: none;
}
/deep/ .ant-tabs-nav .ant-tabs-tab:nth-last-child(1) {
  border-right: 0;
}
/deep/ .ant-tabs-nav .ant-tabs-tab-active {
  position: relative;
  top: 0;
  height: 28px;
  padding-top: 3px;
  line-height: 23px;
  background: #0b61ff;
  border-radius: 6px;
  color: #fff;
  z-index: 10;
}
/deep/ .ant-tabs-nav-container {
  margin-bottom: 12px;
}
/deep/ .ant-tabs-ink-bar {
  display: none !important;
}
/deep/ .ant-tabs-bar {
  border: none;
}
.empty-box {
  margin: 25% 0 35%;
}
/deep/ .checked-td-of-add-table {
  background: #e8f0fc;
  // box-shadow: 0px 2px 14px 0px rgba(42, 68, 103, 0.18);
  border-top: 2px solid #0b61ff;
  border-bottom: 2px solid #0b61ff !important;
}
/deep/ .checked-td-of-add-table:first-child {
  border-left: 2px solid #0b61ff !important;
}
/deep/ .checked-td-of-add-table:last-child {
  border-right: 2px solid #0b61ff !important;
}
/deep/ .ant-spin-container {
  width: 100%;
}
.content-wapper {
  width: 100%;
  min-height: 768px;
  padding: 16px 14px 0 14px;
  position: relative;
  top: 0;
  background: #fff;
  min-height: 100%;
}

.color-f55 {
  color: #f55f4e !important;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
.multi-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; // 超出两行则以...形式隐藏
  -webkit-box-orient: vertical;
}
.ztDis_box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.zt_discrible_btn {
  color: #0090ff;
  cursor: pointer;
}

.zt_discrible_solution_list {
  list-style: none;
}
.all-data {
  background: #ffffff;
  box-shadow: 1px 0px 0px 0px #f6f6f6;
  border-radius: 4px;
  margin: 16px 0;
  border: 1px solid #f6f6f6;
  .data-item {
    position: relative;
    display: flex;
    padding-left: 50px;
    .img-box {
      position: absolute;
      left: 0;
      top: 0;
    }

    &-item {
      width: calc(100% / 3);
      padding: 16px 0;
      text-align: center;
      border-right: 1px solid #f6f6f6;
    }
    &-item:last-child {
      border: none;
    }
  }
  .total-data {
    border-bottom: 1px solid #f6f6f6;
    .img-box {
      width: 45px;
      height: 40px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .today-data {
    .img-box {
      width: 50px;
      height: 50px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
